<?php

/**
 *类名：iapPayTrade.php
 *功能  CP服务器端处理爱贝平台交易返回
 *版本：1.0
 *日期：2014-06-26
'说明：
 */

date_default_timezone_set('Asia/Shanghai');
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);

include_once("./IapppayCpSyncForPHP/base.php");
include_once("./IapppayCpSyncForPHP/config.php");
include_once("./mysql.class.php");
include_once("./redis.class.php");
include_once("./connConfig.php");
include_once("./httpclient.php");

function recv_post_data() {
	$PostData = file_get_contents("php://input") ? file_get_contents("php://input") : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);
	return $PostData;

}

function record_post_data($PostData) {
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', $PostData);
}

function parse_post_data($PostData) {
    $platpkey = ibconfig::$platpkey;
	if(!ipbase::parseResp($PostData, $platpkey, $respJson)) {
        //error_log('1121212'."\n\r", 3, 'error.log');
		echo "parse resp data failed!\n";
	}else{
        //error_log('56565656'."\n\r", 3, 'error.log');
        echo 'success';
    }
	return $respJson;
}

function connect_db(&$redis, &$mysql, $uid) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
        echo("mysql connect error.\n");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
        exit(0);
    }

    $ret = $redis->initDataRedis($uid);
    if(!$ret) {
        echo("data redis connect error.\n");
        exit(0);
    }
}

function process($respJson,&$payInfArr, &$redis, &$mysql) {
    //错误返回
    if ( isset($respJson->code) ) {
       // echo $respJson->code;
        //echo $respJson->errmsg;
        echo "FAILURE";
        exit(0);
    }

    //正确返回
    $cporderid = (string)$respJson->cporderid;
    $transid = (string)$respJson->transid;
    $uid = (int)$respJson->appuserid;
    $appid = (string)$respJson->appid;
    $goodsid = (int)$respJson->waresid;
    $feetype = (int)$respJson->feetype;
    $rmb = (float)$respJson->money;
    $result = (int)$respJson->result;
    $transtime = (string)$respJson->transtime;

    if ($result != 0){
        //echo $result;
        echo "FAILURE";
        exit(0);
    }

    $row = $mysql->select('applypay','*',array('order_id' => $cporderid));
    $goodsid=$row[0]['goods_id'];
    if ( count($row) == 0) {
        //echo("order not exist.\n");
        echo "FAILURE";
        exit(0);
    }

    $payInfArr = $row[0];
    //var_dump($payInfArr);
    //$uid = (int)$payInfArr['uid'];
    $is_send = (int)$payInfArr['is_send'];

    //var_dump($uid,$is_send);

    if ($is_send == 1) {
        echo "repead order.";
        echo "FAILURE";
        exit(0);
    }


    $data = array(
        'is_send' => 1,
        'type' => 1,
        'iap_transaction_id'=>$transid,
        'update_time' => date('Y-m-d H:i:s',time())
    );
    //$logger->info('applePayTrade', json_encode($data));
    //充值成功后改变状态；

    $mysql->update('applypay',$data,array('order_id' => $cporderid) );;



    //处理充值，加金币或道具
/*    $goodsid=$goods[0]['id'];
    $logger->info('goodsid', $goods[0]['id']);*/
    $redis->initDataRedis($uid);
    $player = $redis->data_redis->hMGet("hu:{$uid}", array('id','user','exp', 'name', 'money', 'coin','isget_coin_task_reward_record'));
    //var_dump($player);

    if($goodsid==7 && $player['isget_coin_task_reward_record']==1){
        exit("你已经购买过此商品,不可购买");
    }

    //处理充值，加金币或道具

    $goodsadd = $redis->cache_redis->hMGet("hg:{$goodsid}", array("money","rmb","propnum","give_money"));
    error_log("goodadd--".json_encode($goodsadd)."\n\r" ,3,"error_s_log");
    $add_coin = (int)($goodsadd['money']);

    if($goodsid>=20 && $goodsid<30){
        $type=1;
        $proop_info=add_porp($goodsid,$uid ,$redis,(int)$player['money'],(int)$goodsadd['give_money'],$mysql,(int)$goodsadd['rmb']);

    }

    if($goodsid>=30 && $goodsid<50){
        error_log("goodsid--".$goodsid."\n\r" ,3,"error_s_log");
        gift_pay($goodsid,$uid ,$redis,(int)$goodsadd['rmb'],$goodsadd['propnum']);
    }
    if($goodsid>=50){
        error_log("goodsid--".$goodsid."\n\r" ,3,"error_s_log");
        gift_money($goodsadd['give_money'],$mysql,$redis,$uid,$player['money'],(int)$goodsadd['rmb']);
    }

    if($goodsid<10){
        if($goodsid==7){
            $exp=10;
            $redis->data_redis->hSet("hu:{$uid}","isget_coin_task_reward_record",1);


            $happy_num=$redis->data_redis->hGet("hu:{$uid}","301_week_happy_num");//查看当前天数
            if($happy_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",6);
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_happy",1);
                $num=$happy_num+6;
                $prop_id=301;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",7);
                $num=$happy_num+7;
                $prop_id=301;
            }

                error_log($num."\n\r" ,3,"error_s_log");

                $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';
                $http = new httpclient();
                $http->Get($url);
                error_log($url."\n\r" ,3,"error_s_log");

        }else{
            $exp=(int)$goodsadd['rmb'];
        }

        //给用户加钻石
        $cur_coin = $redis->data_redis->hincrBy("hu:{$uid}","coin",$add_coin);

        //给用户加经验
        $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
        $ret=$redis->data_redis->hMget("hu:{$uid}",array("coin","money","exp"));

        //var_dump($ret);
        //写入变化记录
        if($cur_coin){
            $info =array();
            $info['type'] = '6';
            $info['uid']    = $uid;
            $info['coin']  = $ret['coin'];
            $info['change_coin'] = $add_coin;
            $info['create_time']  = time();
            $mysql->insert("coin_change_rec",$info);//写入金币变化表；
        }else{

            $this->returnData(array(),588,'redis写入失败');
        }

    }


    //插入充值记录
    $pyinfo = array('uid'=>$uid,'rmb'=>$rmb,'goodsid'=>$goodsid,'type'=>10,'create_time'=>time());

    $mysql->insert('payrecord', $pyinfo);

    $num=$proop_info['num'];
    $prop_id=$proop_info['prop_id'];


    $http = new httpclient();

    if($goodsid<10){
        $type=2;
        $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"coin":'.$ret['coin'].'}';
    }else{
        $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';
    }
error_log($url."\n\r" ,3,"error_s_log");
    $http->Get($url);

}


//充值增加道具
function add_porp($goodsid,$uid,$redis,$money,$give_money,$mysql,$exp){
    switch($goodsid){
        case 21:
            $happy_num=$redis->data_redis->hGet("hu:{$uid}","301_week_happy_num");//查看当前天数
            if($happy_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",6);
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_happy",1);
                $num=$happy_num+6;
                $prop_id=301;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",7);
                $num=$happy_num+7;
                $prop_id=301;
            }
            $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
            break;
        case 22:

            $redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);//增加赠送的金币
            $overflow_num=$redis->data_redis->hGet("hu:{$uid}","302_week_overflow_num");//查看当前天数
            if($overflow_num==0){
                $redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",6);//改变天数
                $redis->data_redis->hSet("hu:{$uid}","is_get_week_overflow",1);//改变可领取状态
                $num=$overflow_num+6;
                $prop_id=302;
            }else{
                $redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",7);//改变天数
                $num=$overflow_num+7;
                $prop_id=302;
            }
            $last_money=$money+$give_money;
            insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
            $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
            break;
    }
    return array('num'=>$num,'prop_id'=>$prop_id);

}

//处理礼包充值
function gift_pay($goodsid,$uid,$redis,$exp,$num){
    $porp_s=array(
        '101_gift_num'=>31,
        '102_gift_num'=>32,
        '103_gift_num'=>33,
        '104_gift_num'=>34,
        '105_gift_num'=>35,
        '106_gift_num'=>36,
    );
    $keys=array_search($goodsid,$porp_s);
    if($keys){
        $redis->data_redis->hincrBy("hu:{$uid}",$keys,$num);
        $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
    }else{
        returnData(array(),588,'商品不存在');
    }

}

//金币礼包
function gift_money($give_money,$mysql,$redis,$uid,$money,$exp){
    $redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);
    $last_money=$money+$give_money;
    insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
    $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
}


function insert_moey($uid,$last_money,$give_money,$mysql){
    //var_dump($give_money);
    $info =array();
    $info['type'] = '6';
    $info['uid']    = $uid;
    $info['money']  = $last_money;
    $info['change_money'] = +$give_money;
    $info['create_time']  = time();
    $mysql->insert("money_change_rec",$info);//写入钻石变化表；
}



function insert_pay_record(&$mysql, $payInfArr) {
    //插入充值记录
    $payrecord = array();
    $payrecord['uid'] = (int)$payInfArr['uid'];
    $payrecord['rmb'] = (float)$payInfArr['price'];
    $payrecord['vercode'] = $payInfArr['version'];
    $payrecord['ua'] = $payInfArr['ua'];
    $payrecord['imsi'] = $payInfArr['imsi'];
    $payrecord['imei'] = $payInfArr['imei'];
    $payrecord['cid'] = $payInfArr['cid'];
    $payrecord['order_id'] = $payInfArr['order_id'];
    $payrecord['type'] = 1;
    $payrecord['create_time'] = time();
    $mysql->insert('payrecord', $payrecord);
}

function sys_task_of_pay($uid,&$redis) {
    //首次冲值奖券任务是否完成
    //从奖券任务记录字段中获取奖券任务完成度
    $task_id = 2;//任务号为2
    $task_complete_record_str = $redis->data_redis->hget("hu:{$uid}", "coin_task_complete_record");
    $task_pieces = explode("|", $task_complete_record_str);
    $task_value = $redis->cache_redis->hget("hcointask:{$task_id}", "task_value");
    //如果任务完成度 < 最大任务完成值,则任务完成度加1
    if ((int)$task_pieces[$task_id - 1] < (int)$task_value) {
        $task_pieces[$task_id - 1] += 1;
        //重新组装，任务奖励记录字符串
        $size = count($task_pieces);
        $str = "";
        for ($i = 0; $i < $size; $i++) {
            $str .= $task_pieces[$i];
            if ($i < $size - 1) {
                $str .= "|";
            }
        }
        //重新设置任务奖励记录字符串
        $redis->data_redis->hset("hu:{$uid}", "coin_task_complete_record", $str);
    }
}

function do_trade() {
	$PostData = recv_post_data();

    //record_post_data($PostData);
    //$PostData = "transdata=%7B%22appid%22%3A%223001552896%22%2C%22appuserid%22%3A%223180%22%2C%22cporderid%22%3A%22ae3542f8e4730553060dcbf4%22%2C%22cpprivate%22%3A%22cpprivateinfo123456%22%2C%22currency%22%3A%22RMB%22%2C%22feetype%22%3A0%2C%22money%22%3A0.010%2C%22paytype%22%3A401%2C%22result%22%3A0%2C%22transid%22%3A%2232081412221436262495%22%2C%22transtime%22%3A%222014-12-22+14%3A36%3A39%22%2C%22transtype%22%3A0%2C%22waresid%22%3A16%7D&sign=p%2FVJqEaovC4Xczdk7wceKKRTQLTVD1E18CxUQCphu8MsxjmHEYFCFpc%2FlxVtg%2BKc4%2Fda%2FOxtSA3bbvEoITmApBWBEMm4%2FzsxsGyy3YIKEVMpPQAqZco5Nw4uky9lqWgwqRt2l5fr5Pq7hWshxWCfzWs3%2B560MRjKyVN2f05EMfg%3D&signtype=RSA";
    //$PostData = "transdata=%7B%22appid%22%3A%223001552896%22%2C%22appuserid%22%3A%223048%22%2C%22cporderid%22%3A%22f6447ed82e60b8b9d8de9ed4%22%2C%22cpprivate%22%3A%22cpprivateinfo123456%22%2C%22currency%22%3A%22RMB%22%2C%22feetype%22%3A0%2C%22money%22%3A0.010%2C%22paytype%22%3A401%2C%22result%22%3A0%2C%22transid%22%3A%2232031412231109363145%22%2C%22transtime%22%3A%222014-12-23+11%3A10%3A20%22%2C%22transtype%22%3A0%2C%22waresid%22%3A16%7D&sign=SpSDU8PeQL0wbFcWr1vGmnqROagRWHxBGYmONwUQB6yEDAlC%2FAHDGyf9qpiL%2BxVwBypO2Ir1k5dE7IIvWvGrbsBH3HgWI738J5IEB9q0M9Twi%2B7tMVPDfC9OQsxUpv4E9xjlNSWcx%2FiNp%2FhXLZlXTVrpu%2Fp4GsxzDE5AbnSItbw%3D&signtype=RSA";
    //$PostData = "transdata=%7B%22appid%22%3A%223001552896%22%2C%22appuserid%22%3A%223177%22%2C%22cporderid%22%3A%22785de73e22f89ca0891c489e%22%2C%22cpprivate%22%3A%22cpprivateinfo123456%22%2C%22currency%22%3A%22RMB%22%2C%22feetype%22%3A0%2C%22money%22%3A0.010%2C%22paytype%22%3A401%2C%22result%22%3A0%2C%22transid%22%3A%2232051412231451223076%22%2C%22transtime%22%3A%222014-12-23+14%3A51%3A56%22%2C%22transtype%22%3A0%2C%22waresid%22%3A15%7D&sign=t7ycYBWB%2FSRN1SgSXDRBbGJVbTCfTPocpXgz30GtW2UsbBCXUfNLWgo%2FaIkMwm9s6%2FiPUHLiKB7ih3xJWUyXo%2B%2Fqjmh0cNhnEFYHKR99tz%2FHJDkyMenLdVtvsTSYVF1a79kzrzJzA%2FzS%2BMGaqO5Z0WRv8LCZzu6%2FleyqLFJvCwA%3D&signtype=RSA";
    $PostData = urldecode($PostData);
    error_log($PostData."\n\r", 3, 'error.log');
    //var_dump($PostData);
	$respJson= parse_post_data($PostData);
    //var_dump($respJson);
    $redis = new RedisDriver();
    $mysql = new MysqlDriver();
    $uid = (int)$respJson->appuserid;
    connect_db($redis, $mysql,$uid);
    process($respJson,$payInfArr,$redis, $mysql);
    //insert_pay_record($mysql,$payInfArr);
    //sys_task_of_pay($uid,$redis);
    $redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
    //error_log("SUCCESS----".""."\n\r", 3, 'error.log');
    echo "SUCCESS";
    exit("SUCCESS");
}

do_trade();

?>
